<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
    <el-form-item :label="$t('menu.admin.user.field.nickname')" prop="nickname">
      <el-input v-model="formData.nickname" />
    </el-form-item>
    <el-form-item :label="$t('menu.admin.user.field.gender')" prop="gender">
      <RaDict v-model="formData.gender" code="gender_options" />
    </el-form-item>
  </el-form>
</template>

<script setup>
import API from '@/api/admin/profile';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';

const props = defineProps({
  initialData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['submit-success', 'submit-cancel']);

const formRef = ref(null);
const formData = reactive({
  id: '',
  nickname: '',
  gender: 1,
});

const rules = {
  nickname: [
    {
      required: true,
      message: $t('menu.admin.user.field.nickname') + '不能为空',
      trigger: 'blur',
    },
  ],
};

// 监听初始数据变化，更新表单数据
watch(
  () => props.initialData,
  (newData) => {
    if (newData && Object.keys(newData).length > 0) {
      formData.id = newData.id || '';
      formData.nickname = newData.nickname || '';
      formData.gender = newData.gender || 1;
    }
  },
  { immediate: true, deep: true },
);

const submitForm = async () => {
  try {
    const valid = await formRef.value.validate();
    if (valid) {
      await API.updateProfile(formData);
      ElMessageBox.alert(
        $t('common.message.success.change', {
          field: $t('menu.profile.field.profile'),
        }),
        $t('common.title.notice'),
        { type: 'success' },
      );
      emit('submit-success');
    }
  } catch (error) {
    console.error('账号资料修改失败:', error);
  }
};

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  // 重置为初始数据
  if (props.initialData && Object.keys(props.initialData).length > 0) {
    formData.id = props.initialData.id || '';
    formData.nickname = props.initialData.nickname || '';
    formData.gender = props.initialData.gender || 1;
  }
};

defineExpose({
  submitForm,
  resetForm,
});
</script>
